package br.com.educa.modelo.publico;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.TypedQuery;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.classpath.operations.jsr303.RooUploadedFile;
import org.springframework.transaction.annotation.Transactional;

import flexjson.JSON;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

@Configurable
@Entity
@Table(schema = "public")
@RooJavaBean
@RooSerializable
@RooToString
@RooJson
@RooJpaActiveRecord(schema = "public", finders = { "findArquivoesByTamanhoEqualsAndNomeEquals" })
public class Arquivo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date dataImagem;

    private String descricao;

    private String nome;

    @RooUploadedFile(contentType = "application/pdf")
    @Lob
    private byte[] conteudo;

    private String contentType;

    private Long tamanho;

    @Transient
    @Size(max = 100)
    private String url;

    @PersistenceContext
    transient EntityManager entityManager;

    public static final EntityManager entityManager() {
        EntityManager em = new Arquivo().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

    public static long countArquivoes() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Arquivo o", Long.class).getSingleResult();
    }

    public static List<Arquivo> findAllArquivoes() {
        return entityManager().createQuery("SELECT o FROM Arquivo o", Arquivo.class).getResultList();
    }

    public static Arquivo findArquivo(Long id) {
        if (id == null) return null;
        return entityManager().find(Arquivo.class, id);
    }

    public static List<Arquivo> findArquivoEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Arquivo o", Arquivo.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

    @Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Arquivo attached = Arquivo.findArquivo(this.id);
            this.entityManager.remove(attached);
        }
    }

    @Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

    @Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

    @Transactional
    public Arquivo merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Arquivo merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Integer getVersion() {
        return this.version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public String toJson() {
        return new JSONSerializer().exclude("*.class").serialize(this);
    }

    public static Arquivo fromJsonToArquivo(String json) {
        return new JSONDeserializer<Arquivo>().use(null, Arquivo.class).deserialize(json);
    }

    public static String toJsonArray(Collection<Arquivo> collection) {
        return new JSONSerializer().exclude("*.class").serialize(collection);
    }

    public static Collection<Arquivo> fromJsonArrayToArquivoes(String json) {
        return new JSONDeserializer<List<Arquivo>>().use(null, ArrayList.class).use("values", Arquivo.class).deserialize(json);
    }

    public Date getDataImagem() {
        return this.dataImagem;
    }

    public void setDataImagem(Date dataImagem) {
        this.dataImagem = dataImagem;
    }

    public String getDescricao() {
        return this.descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getNome() {
        return this.nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getContentType() {
        return this.contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public Long getTamanho() {
        return this.tamanho;
    }

    public void setTamanho(Long tamanho) {
        this.tamanho = tamanho;
    }

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @JSON(include=false)
	public byte[] getConteudo() {
		return conteudo;
	}

    public InputStream getInputStream() {
		return new ByteArrayInputStream(conteudo);
	}
    
	public void setConteudo(byte[] conteudo) {
		this.conteudo = conteudo;
	}

	public static TypedQuery<Arquivo> findArquivoesByTamanhoEqualsAndNomeEquals(Long tamanho, String nome) {
        if (tamanho == null) throw new IllegalArgumentException("The tamanho argument is required");
        if (nome == null || nome.length() == 0) throw new IllegalArgumentException("The nome argument is required");
        EntityManager em = Arquivo.entityManager();
        TypedQuery<Arquivo> q = em.createQuery("SELECT o FROM Arquivo AS o WHERE o.tamanho = :tamanho  AND o.nome = :nome", Arquivo.class);
        q.setParameter("tamanho", tamanho);
        q.setParameter("nome", nome);
        return q;
    }
}
